package com.blyat.xsoft.gateway.autoconfigurator;

import com.blyat.xsoft.gateway.security.XSoftAuthenticationWebFilter;
import com.blyat.xsoft.gateway.security.core.XSoftReactiveAuthenticationManager;
import com.blyat.xsoft.gateway.security.core.XSoftReactiveAuthorizationManager;
import com.blyat.xsoft.gateway.security.core.XSoftServerAuthenticationEntryPoint;
import com.blyat.xsoft.gateway.security.refresher.JwtReactiveTokenRefresher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @Auther: syh
 * @Date: 2020/8/27
 * @Description:
 */
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class AuthorizationConfiguration {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private XSoftReactiveAuthorizationManager authorizationManager;

    @Bean
    public SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) throws Exception {
        http
                .httpBasic().disable()
                .csrf().disable()
                .authorizeExchange()
                .pathMatchers(HttpMethod.OPTIONS).permitAll()
                .anyExchange().access(authorizationManager)
                .and()
                .exceptionHandling().authenticationEntryPoint(xSoftServerAuthenticationEntryPoint())
                .and()
                // 跨域过滤器
                .addFilterAt(corsFilter(), SecurityWebFiltersOrder.CORS)
                //oauth2认证过滤器
                .addFilterAt(authenticationWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION);
        return http.build();
    }

    @Bean
    public XSoftServerAuthenticationEntryPoint xSoftServerAuthenticationEntryPoint() {
        return new XSoftServerAuthenticationEntryPoint();
    }

    private AuthenticationWebFilter authenticationWebFilter() {
        XSoftReactiveAuthenticationManager tokenAuthenticationManager = new XSoftReactiveAuthenticationManager(tokenStore);
        JwtReactiveTokenRefresher executor = new JwtReactiveTokenRefresher();
        // executor.setClientService();
        executor.setTokenStore(tokenStore);
        tokenAuthenticationManager.setExecutor(executor);
        XSoftAuthenticationWebFilter authenticationWebFilter = new XSoftAuthenticationWebFilter(tokenAuthenticationManager);
        authenticationWebFilter.setServerAuthenticationConverter(new ServerBearerTokenAuthenticationConverter());
        authenticationWebFilter.setAuthenticationFailureHandler(
                new ServerAuthenticationEntryPointFailureHandler(xSoftServerAuthenticationEntryPoint()));
        return authenticationWebFilter;
    }

    /**
     * 跨域配置
     */
    public WebFilter corsFilter() {
        return (ServerWebExchange ctx, WebFilterChain chain) -> {
            ServerHttpRequest request = ctx.getRequest();
            if (CorsUtils.isCorsRequest(request)) {
                HttpHeaders requestHeaders = request.getHeaders();
                ServerHttpResponse response = ctx.getResponse();
                HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
                HttpHeaders headers = response.getHeaders();
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
                headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
                if (requestMethod != null) {
                    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
                }
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
                headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
                headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "18000L");
                if (request.getMethod() == HttpMethod.OPTIONS) {
                    response.setStatusCode(HttpStatus.OK);
                    return Mono.empty();
                }
            }
            return chain.filter(ctx);
        };
    }
}
